import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { User, Post, Prisma } from '@prisma/client';
import { UsersDto } from './dto';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) { }

  async user(user: Prisma.UserWhereUniqueInput): Promise<User | null> {
    return this.prisma.user.findUnique({ where: user })
  }

  async users(skip: number, take: number): Promise<UsersDto> {
    let count = await this.prisma.user.count()
    let data = await this.prisma.user.findMany({ take, skip })
    return { count, data }
  }

  async createUser(data: Prisma.UserCreateInput): Promise<User> {
    return this.prisma.user.create({ data })
  }

  async updateUser(params: { where: Prisma.UserWhereUniqueInput, data: Prisma.UserUpdateInput }): Promise<User> {
    const { where, data } = params
    return this.prisma.user.update({ where, data })
  }

  async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {
    return this.prisma.user.delete({ where })
  }

  async getUserPosts(user: Prisma.UserWhereUniqueInput): Promise<Post[]> {
    return this.prisma.user.findUnique({ where: user }).posts()
  }
}
